<template>
  <div class="iframe_box">
    <nut-drag
      @click.stop="onBtnClicked"
      style="width: 46px; height: 46px; top: 0px"
      :style="{ top: state.boundary.top + 'px' }"
      v-if="state.showDrag"
      class="drag"
      attract
      :boundary="state.boundary"
    >
      <iconpark-icon name="home" size="30" />
    </nut-drag>
    <div class="loading-content" v-if="loading">
      <SvgaItem keyStr="1" name="game_loading" :active="true" class="tab_style" />
    </div>
    <Modal v-model:visible="backConfirmVisible" :title="t('tip')">
      <div class="modal_body">
        <div class="content">
          {{ t('home_leave_game') }}
        </div>
        <div class="btns-wrap">
          <Btn
            v-shrink-on-click
            class="submit btn-cancel"
            @click="backConfirmVisible = false">{{ t('cancel') }}
          </Btn>
          <Btn
            v-shrink-on-click
            class="submit"
            @click="leaveGame">{{ t('confirm') }}
          </Btn>
        </div>
        
      </div>
    </Modal>
    <div v-if="state.src && !loading" class="thirdPartyGameClass">
      <div v-if="state.src.startsWith('<!DOCTYPE html>')" class="htmlClass">
         <iframe
          id="iframeId"
          :srcdoc="state.src"
          frameborder="0"
          scrolling="auto"
          allow="cookies"
          sandbox="allow-same-origin allow-scripts allow-storage-access-by-user-activation allow-forms"
        />
      </div>
      <div class="iframeClass" v-else>
        <iframe
          id="iframeId"
          :src="state.src"
          frameborder="0"
          scrolling="auto"
          allow="cookies"
          sandbox="allow-same-origin allow-scripts allow-storage-access-by-user-activation allow-forms"
        />
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { Local } from "@/utils/storage";
import { onMounted, onUnmounted, reactive, defineAsyncComponent, ref } from "vue";
import { useRouter } from "vue-router";
import PKwebsocket from "@/lolo/Ws";
import pinia from '@/store/index';
import { Page } from '@/store/page';
import { useI18n } from "vue-i18n";
import { NetPacket } from "@/netBase/NetPacket";
import eventBus from "@/lolo/eventBus";
const { t } = useI18n();
const SvgaItem = defineAsyncComponent(() => import("@/components/SvgaItem.vue"));
const router = useRouter();
const loading = ref(false);
const state: any = reactive({
  showDrag: true,
  src: "",
  left: "",
  top: 0,
  boundary: { top: 0, left: 0, bottom: 20, right: 0 },
  rlen: history.length,
});
const backConfirmVisible = ref(false);
const onBtnClicked = () => {
  backConfirmVisible.value = true
};

const leaveGame = () => {
  backConfirmVisible.value = false
  let len = state.rlen - history.length - 1;
  router.go(len);
  Page(pinia).setBackFromGame(true);
  // 进入游戏的时候断开了ws,退出的时候重连ws
  PKwebsocket.instance.reConnectWs();
  eventBus.on('wsopen', wsOpenHandler);
}

// 监听ws重连成功事件
const wsOpenHandler = () => {
  console.log('WebSocket重连成功');
  syncNewData();
  eventBus.off('wsopen', wsOpenHandler);
};

function syncNewData(){
    let tb = NetPacket.req_3rd_game_kick();
    let item = Local.get("selectedGameItem");
    tb.agentId = item.agentId || item.id 
    tb.gameId = item.gameId 
    PKwebsocket.instance.send(tb,true);

    let count = 0;
    const sendRefreshRequest = () => {
        const req = NetPacket.req_refresh_money();
        PKwebsocket.instance.send(req, true);
        count++;
        
        if (count < 3) {
            setTimeout(sendRefreshRequest, 1000);
        }
    };

    setTimeout(sendRefreshRequest, 2000);
}
const resizeChange = () => {
  state.showDrag = false;
  setTimeout(() => {
    state.showDrag = true;
  }, 200);
  // if (window.orientation === 90 || window.orientation === -90) {
  //   state.show = false

  // } else {
  //   state.show = true
  // }
};
const isStandaloneMode = () => {
  const isIOS = /iphone|ipad|ipod/i.test(window.navigator.userAgent);
  const isStandalone =
    window.matchMedia("(display-mode: standalone)").matches ||
    window.navigator.standalone;
  if (isStandalone) {
    state.boundary.top = 30;
    console.log("主屏幕模式 (PWA)");
  } else if (isIOS) {
    state.boundary.top = 0;
    console.log("普通浏览器模式 (iOS)");
  } else {
    state.boundary.top = 0;
    console.log("普通浏览器模式");
  }
};
const event = "onorientationchange" in window ? "orientationchange" : "resize";
onMounted(() => {
  // document.removeEventListener("scroll", stopMove);
  // document.body.style.overflow = "auto";
  document.body.style.height = "200vh";
  isStandaloneMode();
  window.scrollTo({
    top: document.body.scrollHeight,
    behavior: "smooth", // 平滑滚动
  });

  setTimeout(() => {
    state.src = Local.get("gameUrl");
    // if(state.src.startsWith('<!DOCTYPE html>')){
    //   dealHtml(state.src)
    // }
  }, 300);
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
  }, 5000);
  Page(pinia).setGameIsLoading(false)
  window.addEventListener(event, resizeChange, false);
});
// function dealHtml(htmlString:string){
//   //三方游戏可能是html
//   console.log('%c@@@@htmlString','background: gray; color: white; font-size: 16px;',htmlString);
//   const parser = new DOMParser();
//   const doc = parser.parseFromString(htmlString, "text/html");

//   document.head.innerHTML += doc.head.innerHTML;


//   // 执行所有 <script>
//   doc.querySelectorAll("script").forEach((script) => {
//     const newScript = document.createElement("script");
//     newScript.textContent = script.textContent;
//     document.body.appendChild(newScript);
//     document.body.removeChild(newScript);
//   });
// }
onUnmounted(() => {
  // document.addEventListener("scroll", stopMove);
  // document.body.style.overflow = "hide";
  document.body.style.height = "auto";
  window.removeEventListener(event, resizeChange, false);
});
</script>

<style lang="scss" scoped>
.loading-content {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 55%;
}
.iframe_box {
  bottom: 0;
  height: 100%;
  left: 0;
  min-height: 0 !important;
  overflow-y: scroll;
  overflow: hidden;
  padding-bottom: 0;
  position: fixed;
  right: 0;
  top: 0;
  width: 100%;
  z-index: 40;
}


.drag {
  background-color: #ccc;
  border-radius: 50%;
  z-index: 9999 !important;
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal_body {
  padding: 20px;
  .content {
    padding: 10px;
    text-align: center;
    min-height: 66px;
  }
  .btns-wrap {
    display: flex;
    justify-content: space-between;
    .submit {
      height: 42px;
      width: 145px;
    }
    .btn-cancel {
      color: #FFFFFF;
      text-align: center;
      line-height: 44px;
      background: #282747;
      box-shadow: 0.5px 0.5px 1px 0px #2E296B inset;
      border-radius: 8px;
    }
  }
}

.back-btn {
  // padding: 30px;
}
.thirdPartyGameClass,.htmlClass,.iframeClass {
  height: 100%;
}
#iframeId {
  height: 100%;
  min-height: 0 !important;
  padding-top: 0;
  position: relative;
  width: 100%;
  z-index: 0;
}
</style>
